<?php

namespace plugin\admin\app\controller;

use app\model\DeviceQualityInfo;
use Carbon\Carbon;
use support\Request;
use support\Response;
use plugin\admin\app\model\Device;
use plugin\admin\app\controller\Crud;
use support\Db;
use support\exception\BusinessException;

/**
 * 设备列表 
 */
class DeviceController extends Crud
{

    /**
     * @var Device
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new Device;
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('device/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            try {
                return parent::insert($request);
                //code...
            } catch (\Throwable $th) {
                //throw $th;
                return $this->json(1, '添加失败');
            }
        }
        return view('device/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('device/update');
    }

    /**
     * 获取设备水质信息
     * @param Request $request
     * @return Response
     */
    public function quality(Request $request): Response
    {
        $id = $request->get('id');
        if (!$id) {
            return $this->json(1, '缺少设备ID');
        }
        $device = Device::find($id);
        if (!$device) {
            return $this->json(1, '设备不存在');
        }

        $end = Carbon::now()->toDateTimeString();
        $start = Carbon::now()->subSeconds(600)->toDateTimeString();

        // dd($start, $end);

        $result = DeviceQualityInfo::query()
            ->where('device_id', $id)
            ->whereBetween('created_at', [$start, $end])
            ->select(Db::raw('AVG(cl) as cl, AVG(ph) as ph, AVG(tds) as tds, AVG(filter) as filter,AVG(water) as water'))
            ->get();

        $result = collect($result)->first();

        // 只返回相关字段
        $data = [
            'cl' => round($result['cl'] ?? 0, 2),
            'ph' => round($result['ph'] ?? 0, 2),
            'tds' => round($result['tds'] ?? 0,0),
            'filter' => round($result['filter'] ?? 0,0),
            'water' => round($result['water'] ?? 0, 2),
            // 'status' => $device->status,
            // 'is_online' => $device->is_online,
            // 'alarm' => $device->alarm,
        ];

        //

        return $this->json(0, 'ok', $data);
    }

    /**
     * 获取设备绑定用户
     * @param Request $request
     * @return Response
     */
    public function bindUsers(Request $request): Response
    {
        $id = $request->get('id');
        if (!$id) {
            return $this->json(1, '缺少设备ID');
        }
        $device = Device::find($id);
        if (!$device) {
            return $this->json(1, '设备不存在');
        }
        $users = $device->users()->select(['nickname', 'phone'])->get();
        return $this->json(0, 'ok', $users->toArray());
    }

    public function select(Request $request): Response
    {
        $format = $request->get('format');
        if ($format === 'select') {
            $devices = Device::all();
            $data = [];
            foreach ($devices as $device) {
                $data[] = [
                    'value' => $device->id,
                    'name' => $device->sn,
                ];
            }
            return $this->json(0, 'ok', $data);
        }
        return parent::select($request);
    }
}
